package cn.good.yan.service.impl;

import cn.good.yan.entity.Order;
import cn.good.yan.mapper.OrderMapper;
import cn.good.yan.service.AccountService;
import cn.good.yan.service.OrderService;
import cn.good.yan.service.StorageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 订单服务
 *
 * @author shengren.yan
 * @create 2024-02-22
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    AccountService accountService;

    @Autowired
    StorageService storageService;

    /**
     * 创建新订单
     * 2.减库存
     * 3.减余额
     * 4.修改订单状态
     *
     * @param order
     */
    @Override
//    @Transactional(rollbackFor = Exception.class)
    @GlobalTransactional(rollbackFor = Exception.class)
    public void create(Order order) {
        log.info("-----> 创建新订单");
        order.setStatus(0); // 状态是 创建中
        orderMapper.insert(order);

        log.info("-----> 开始减库存");
        // 参数：产品id、数量
        storageService.decrease(order.getProductId(), order.getCount());
        log.info("-----> 结束减库存");

        log.info("-----> 开始减余额");
        // 参数：账户id、金额
        accountService.decrease(order.getUserId(), order.getMoney());
        log.info("-----> 结束减余额");

        log.info("-----> 开始更新订单状态");
        order.setStatus(1);  // 状态是 创建完成
        orderMapper.updateById(order);
        log.info("-----> 结束更新订单状态");
    }

}
